package com.glela.order.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.glela.api.logistics.juhe.JuheApi;
import com.glela.api.logistics.juhe.vo.JuHeApiVo;
import com.glela.common.util.DateUtil;
import com.glela.common.util.DateUtils;
import com.glela.order.mapper.LogisticsStatusMapper;
import com.glela.order.mapper.OrderInfoMapper;
import com.glela.order.model.LogisticsStatus;
import com.glela.order.model.OrderInfo;
import com.glela.order.service.LogisticsStatusService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;

@Service("logisticsStatusService")
public class LogisticsStatusServiceImpl implements LogisticsStatusService {
	private static final Logger				logger	= LoggerFactory.getLogger(LogisticsStatusServiceImpl.class);
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private LogisticsStatusMapper LogisticsStatusMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Override
    public ResponseEntity<?> getLogisticsEntity(String orderSn) {
        LogisticsStatus logisticsStatus = getLogisticsPojo(orderSn);
        if (logisticsStatus == null) {
            return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20152), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(new ResponseResultModel<LogisticsStatus>(logisticsStatus), HttpStatus.OK);
        }
    }

    @Override
	public LogisticsStatus getLogisticsPojo(String orderInfoSn) {
        return getLogisticsPojo(orderInfoMapper.selectOrderInfoEntityByOrderSn(orderInfoSn));
    }

    public LogisticsStatus getLogisticsPojo(OrderInfo orderInfo) {
        if (orderInfo == null) {
            return null;
        }
        // 查询当前物流信息
        LogisticsStatus logisticsStatus = LogisticsStatusMapper.selectLogisticsEntity(orderInfo.getOrderSn());
        //未找到物流信息 开始初始化
        if (logisticsStatus == null) {
            JuHeApiVo juHeApiVo = getExpress(orderInfo);
            if (juHeApiVo.getList() == null) {
                return null;
            }
            //对象转json
            String json = JSONObject.toJSONString(juHeApiVo);//将java对象转换为json对象
            // 如果没有就把聚合中查出来的添加进去
            LogisticsStatusMapper.insertLogisticsStatus(orderInfo.getOrderSn(), json,
                    Integer.parseInt(juHeApiVo.getStatus()), DateUtil.currentStringDate(), juHeApiVo.getCom(), juHeApiVo.getNo());
            //如果公司不对 需要更新订单上的公司
            if (!StringUtils.equals(juHeApiVo.getCom(), orderInfo.getExpressCode())) {
                orderInfoMapper.updateExpressCompanyByOrderSn(juHeApiVo.getCom(), juHeApiVo.getCompany(), orderInfo.getOrderSn());
            }
            // 从聚合查出来添加之后再查询一次并且返回
            return LogisticsStatusMapper.selectLogisticsEntity(orderInfo.getOrderSn());
        }
        try {
            long date1 = sdf.parse(logisticsStatus.getUpdateTime()).getTime();
            long date2 = sdf.parse(DateUtil.currentStringDate()).getTime();
            if ((date2 - date1) / 1000 / 60 / 60 <= 6 || logisticsStatus.getIsFinish().intValue() == 1) {
                return logisticsStatus;
            }
        } catch (Exception e) {
        }
        // 从子订单中获取快递公司编号和快递号去调用聚合接口查询物流
        JuHeApiVo juHeApiVo = JuheApi.getExp(orderInfo.getExpressCode(), orderInfo.getExpressNo());
        if (juHeApiVo.getList() == null) {
            return null;
        }
        String json = JSONObject.toJSONString(juHeApiVo);//将java对象转换为json对象
        //
        JuHeApiVo vo = JSONObject.parseObject(json, JuHeApiVo.class);
        // 如果没有就把聚合中查出来的添加进去
        LogisticsStatusMapper.updateLogisticsStatus(json,
                Integer.parseInt(vo.getStatus()), DateUtil.currentStringDate(), orderInfo.getOrderSn());
        // 修改完毕之后再查一次并返回
        return LogisticsStatusMapper.selectLogisticsEntity(orderInfo.getOrderSn());
    }

    /**
     * 获取物流信息
     *
     * @param orderInfo
     * @return
     */
	protected JuHeApiVo getExpress(OrderInfo orderInfo) {
		//校验必传字段
		if (orderInfo == null) {
			logger.warn("订单查询物流信息缺少必传参数");
			return new JuHeApiVo();
		}
		if (StringUtils.isAnyBlank(orderInfo.getExpressCode(), orderInfo.getSendTime())) {
			logger.warn("订单[{}]查询物流信息缺少必传参数", orderInfo.getOrderSn(), orderInfo.getExpressCode(), orderInfo.getSendTime());
			return new JuHeApiVo();
		}

		JuHeApiVo juHeApiVo = JuheApi.getExp(orderInfo.getExpressCode(), orderInfo.getExpressNo());
		if (juHeApiVo.getList() == null && DateUtils.compare_date_HHmmss(DateUtils.format(DateUtils.addDay(new Date(), -2), "yyyy-MM-dd HH:mm:ss"), orderInfo.getSendTime()) > 0) {//有可能是公司错误 已经发货两天了
			List<String> companyNoList = LogisticsStatusMapper.getAllExpressCompany();
			for (String company_no : companyNoList) {
				juHeApiVo = JuheApi.getExp(company_no, orderInfo.getExpressNo());
				if (juHeApiVo.getList() != null) {
					break;
				}
			}
		}
		return juHeApiVo;
	}

    @Override
    public LogisticsStatus getLogisticsEntityShouhou(String com, String no) {
        // TODO Auto-generated method stub
        // 根据订单号查询子订单信息
        OrderInfo orderInfo = orderInfoMapper.selectOrderInfoEntityByExpressCodeAndexpressNo(com, no);
        // 查询当前物流信息
        LogisticsStatus logisticsStatus = LogisticsStatusMapper.selectLogisticsEntity(orderInfo.getOrderSn());
        if (logisticsStatus == null) {
            // 从子订单中获取快递公司编号和快递号去调用聚合接口查询物流
            JuHeApiVo juHeApiVo = JuheApi.getExp(orderInfo.getExpressCode(), orderInfo.getExpressNo());
            //对象转json
            String json = JSONObject.toJSONString(juHeApiVo);//将java对象转换为json对象
            //
            JuHeApiVo vo = JSONObject.parseObject(json, JuHeApiVo.class);
            // 如果没有就把聚合中查出来的添加进去
            LogisticsStatusMapper.insertLogisticsStatus(orderInfo.getOrderSn(), json,
                    Integer.parseInt(vo.getStatus()), DateUtil.currentStringDate(), vo.getCom(), vo.getNo());
            // 从聚合查出来添加之后再查询一次并且返回
            LogisticsStatus logisticsStatus1 = LogisticsStatusMapper.selectLogisticsEntity(orderInfo.getOrderSn());
            return logisticsStatus1;
        }
        try {
            long date1 = sdf.parse(logisticsStatus.getUpdateTime()).getTime();
            long date2 = sdf.parse(DateUtil.currentStringDate()).getTime();
            if ((date2 - date1) / 1000 <= 6) {
                return logisticsStatus;
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        // 从子订单中获取快递公司编号和快递号去调用聚合接口查询物流
        JuHeApiVo juHeApiVo = JuheApi.getExp(orderInfo.getExpressCode(), orderInfo.getExpressNo());
        //对象转json
        String json = JSONObject.toJSONString(juHeApiVo);//将java对象转换为json对象
        //
        JuHeApiVo vo = JSONObject.parseObject(json, JuHeApiVo.class);
        // 如果没有就把聚合中查出来的添加进去

        LogisticsStatusMapper.updateLogisticsStatus(json,
                Integer.parseInt(vo.getStatus()), DateUtil.currentStringDate(), orderInfo.getOrderSn());
        // 修改完毕之后再查一次并返回
        LogisticsStatus logisticsStatus2 = LogisticsStatusMapper.selectLogisticsEntity(orderInfo.getOrderSn());
        return logisticsStatus2;
    }


}
